﻿$ErrorState = 2
$ErrorMessage = ""
$Trace = ""
$Value = ""
$Error.Clear()

$virstoNamespace = "root\virtualization\storage"
$virstoServerClass = "Virsto_VSServer"
$virstoVDiskMountClass = 'Virsto_VSVDiskMount'
$virstoVDiskClass = 'Virsto_VSVDisk'
$createMountPointWaitTimeout = 60000
$disk = ""
$diskId = '%DISKID%'
$vhdFile = '%VHDFILENAME%'

try {
                	
    $Trace += 'Connecting to Virsto...  \n'
            
    $vdisk1 = gwmi -query "select * from Virsto_VSVDisk where Id=$diskId" -namespace $virstoNamespace
    if ($vdisk1 -eq $null) {
		$ErrorState = 1
		$Trace += 'Virsto Disk not exists...  \n'
    }
    else
    {

#		$Trace += 'Virsto Disk exists...  \n'

		$diskMountPoints = $vdisk1.GetRelationships('Virsto_VSVDiskMount')
		if ($diskMountPoints.Count -gt 0)
		{

#			$Trace += 'Virsto Disk is mounted. Unmounting vDisk... \n'
#			foreach ($diskMountPoint in $diskMountPoints)
#			{
#				$diskMountPoint.Delete()
#			}
#			$Trace += 'Virsto Disk has been unmounted.'

			$ErrorState = 0
			$Trace += 'vDisk is already mounted. \n'
			$disk = 'C:\ProgramData\Virsto\VHDDir\' + $vhdFile

		}
		else
		{

			$Trace += 'Mounting Virsto Disk...  \n'

			$createMountPointResult = $vdisk1.CreateMountPoint($vhdFile)
			while ($true)
			{
				$isCreatedOnAllNodes = Invoke-WmiMethod -Namespace $virstoNamespace -Path $createMountPointResult.MountPoint -Name 'IsCreatedOnAllNodes'
				if ($isCreatedOnAllNodes.IsCreated)
				{
					$ErrorState = 0
					$Trace += 'vDisk has been mounted. \n'
					$disk = 'C:\ProgramData\Virsto\VHDDir\' + $vhdFile
					break
				}
      
				if ($createMountPointWaitTimeout -lt 0) 
				{
					$ErrorState = 1
					$Trace += 'Virsto Disk has not been mounted on all nodes yet. \n'
					$disk = ''
					break
				}
      
				Start-Sleep -Milliseconds 1000
				$createMountPointWaitTimeout = $createMountPointWaitTimeout - 1000
			}
		}

    }
}
catch {
    $ErrorState = 2
    $ErrorMessage = $error[0].Exception.ToString()
}
Finally {
    $Trace += 'ErrorState:  ' + $ErrorState + ' \n'
    $Trace += 'ErrorMessage: ' + $ErrorMessage + ' \n'
    $Trace += 'MountPath: ' + $disk + ' \n'
	
}

            
$Results = @($ErrorState, $ErrorMessage, $Trace, $disk) 
Return $Results